const phrases = ["这是第一个单词", "这是第二个单词", "这是第三个单词", "这是第四个单词", "这是第五个单词", "这是第六个单词", "这是第七个单词", "这是第八个单词", "这是第九个单词", "这是第十个单词"];
Page({
    data: {
        pageIndex: 0,
        pageCount: phrases.length, //动态获取页面数量
        phrases: phrases,
        Check: 0,
        userId: '',
        // wordList: [],
        transformedDataArray: [],
        btnStatus: [],             // 存储每个页面按钮的状态
        userInfo: null,
        bookId: null,
    },
    swipeChange: function(e) {
        var current = e.detail.current;
        this.setData({

        })
        if(current === 0 || current === this.data.pageCount-1) { //注意数组是从0开始的
            wx.showToast({ 
                title: current === 0 ? '这是第1个了' : '这是最后一个了，让我们开始测验叭',
                icon: 'none',
            });
        }
        this.setData({
            pageIndex: current
        });
        if(current === this.data.pageCount-1) { //注意数组是从0开始的
            let that=this;
            setTimeout(function() {
                that.setData({
                    Check: 1,
                });
              }, 2000); // 2000毫秒即2秒
        }
        
        if(current != this.data.pageCount-1) { //注意数组是从0开始的
            this.setData({
                Check: 0
            });
        }




    },
    continueReview: function() {
        //暂无需操作
    },
    startTest: function() {
        wx.navigateTo({
            url: '/path/to/new/page', //将'/path/to/new/page'替换为你的页面路径
        });
    },


    toWordDetail: function() {
        // 获取当前页面序号对应的数据
        var dataToStore = this.data.transformedDataArray[this.data.pageIndex];
        console.log(this.data.pageIndex)
        // 存储到微信的缓存中
        try {
          wx.setStorageSync('WordDetail', dataToStore);
        //   wx.navigateTo({
        //     url: '/path/WordDetail/WordDetail', 
        //   });
        var dataFromCache = wx.getStorageSync('WordDetail');
  if (dataFromCache) {
    // 使用缓存数据
    console.log(dataFromCache);
  }
        } catch (e) {
          wx.showToast({
            title: '数据存储失败',
            icon: 'none',
            duration: 2000
          });
        }
       // wx.navigateTo({
       //   url: '/pages/Cheshi6/Cheshi6',//需要改成详细页的url
       // })
      },

      addWordToNotebook: function() {
          console.log(this.data.userInfo.uuid)
          console.log(this.data.transformedDataArray[this.data.pageIndex])
          console.log(this.data.transformedDataArray[this.data.pageIndex].word_id)
          console.log(this.data.pageIndex)
        wx.request({
          url: 'http://47.95.223.130:8083/Custom/add',
          method: 'POST',
          data: {
            userId: this.data.userInfo.uuid,
            word: JSON.stringify(this.data.transformedDataArray[this.data.pageIndex]),
            word_id: this.data.transformedDataArray[this.data.pageIndex].word_id,
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: res => {
            console.log(res);
            if (res.data.code === 200) {
              wx.showToast({
                title: '已收藏',
                icon: 'success',
                duration: 1000
              });
            } else {
              wx.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 2000
              });
            }
          },
          fail: res => {
            wx.showToast({
              title: '网络请求失败',
              icon: 'none',
              duration: 2000
            });
          }
        });
      },



    onLoad: function (options) {
        var userInfo = wx.getStorageSync('userInfo');
        var bookId = wx.getStorageSync('bookId');
        this.setData({ 
            userInfo: userInfo,
            bookId: bookId,
        });
        console.log(this.data.userInfo)
        console.log(this.data.bookId)

        var userId1 = wx.getStorageSync('userId');
          this.setData({
            userId: userId1,
          })
          console.log(this.data.userId)
          wx.request({
            url: 'http://47.95.223.130:8083/Word/request',
            data: {
              userId: this.data.userInfo.uuid,
              bookId: this.data.bookId,
            },
            method: "POST",
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            
            success: res => {
                console.log(this.data.userInfo.uuid)
                console.log(this.data.bookId)
            //   resolve(res);
              console.log(res);


                let transformedData = [];

                res.data.data.forEach(item => {
                    let parsedWord = JSON.parse(item.word);
  
                    parsedWord.word_id = item.word_id;

                    transformedData.push(parsedWord);

                    // 在这里进行网络请求，为每一个item添加单词到测试本中
                    // 在此可以执行获取数据、初始化等操作
    // 例如，初始化按钮状态数组
                    let initStatus = Array(transformedData.length).fill(false);
                    this.setData({
                        btnStatus: initStatus
                    });



                });

                

                // 将处理后的数组存储到data中
                this.setData({
                    transformedDataArray: transformedData
                });
                console.log(this.data.transformedDataArray)


            },
            fail: res => {
              reject('失败啦')
            }
          })
    

      },  


      // 处理按钮点击事件
  toggleBtnAndSendRequest: function(e) {
    let index = e.currentTarget.dataset.index;  // 从data-index中获取index
    let currentStatus = this.data.btnStatus[index];  // 获取当前页面的按钮状态
    let newStatus = !currentStatus;  // 翻转状态
    
    let apiUrl = newStatus ? 'http://47.95.223.130:8083/Custom/add' : 'http://47.95.223.130:8083/Custom/del';  // 根据状态选择API
    // console.log(JSON.stringify(this.data.transformedDataArray[index]))
    wx.request({
      url: apiUrl,
      method: 'POST',
      data: {
        userId: this.data.userInfo.uuid,
        word: JSON.stringify(this.data.transformedDataArray[index]),
        word_id: this.data.transformedDataArray[index].word_id,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        //  console.log(JSON.stringify(this.data.transformedDataArray[index]))
        //  console.log(this.data.transformedDataArray[index].word_id)
        console.log(res);
        console.log(this.data.transformedDataArray[index].word_id)
        if (res.data.code === 200) {
            console.log(res.data.message)
          
        }
      },
      fail: res => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none',
          duration: 2000
        });
      }
    });

    // 更新这个页面的状态
    this.setData({
      [`btnStatus[${index}]`]: newStatus
    });
  },



      sendRequestForItem: function(item) {
        wx.request({
            url: 'http://47.95.223.130:8083/Word/finish',
            method: 'POST',
            data: {
                userId: this.data.userInfo.uuid,
                bookId: this.data.bookId,
                word_id: item.word_id,// 这里我假设每个item中都有parsedWord属性
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success: res => {
                console.log(res);
                if (res.data.code === 200) {
                    console.log(res)
                    // 操作成功后的处理
                } else {
                    console.error('背完单词添加失败：');
                }
            },
            fail: res => {
                console.error('网络请求失败：');
            }
        });

        wx.request({
            url: 'http://47.95.223.130:8083/Exam/add',
            method: 'POST',
            data: {
                userId: this.data.userInfo.uuid,
                word_id: item.word_id,
                word: JSON.stringify(item) // 这里我假设每个item中都有parsedWord属性
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success: res => {
                console.log(res);
                if (res.data.code === 200) {
                    // 操作成功后的处理
                } else {
                    console.error('测试单词添加失败：');
                }
            },
            fail: res => {
                console.error('网络请求失败：');
            }
        });
    },
    
    examClick: function() {
        this.data.transformedDataArray.forEach(item => {
            this.sendRequestForItem(item);
        });
        wx.navigateTo({
            url: '/pages/exam/exam', 
        });
    },
    



      /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }

});
